package com.bigfans.searchservice.listener;

import com.bigfans.framework.es.ElasticTemplate;
import com.bigfans.framework.es.IndexDocument;
import com.bigfans.framework.es.request.CreateDocumentCriteria;
import com.bigfans.model.event.BrandCreatedEvent;
import com.bigfans.framework.kafka.KafkaConsumerBean;
import com.bigfans.framework.kafka.KafkaListener;
import com.bigfans.searchservice.api.clients.CatalogServiceClient;
import com.bigfans.searchservice.model.Brand;
import com.bigfans.searchservice.model.Category;
import com.bigfans.searchservice.schema.mapping.BrandMapping;
import com.bigfans.searchservice.schema.mapping.CategoryMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author lichong
 * @create 2018-02-10 下午2:03
 **/
@Component
@KafkaConsumerBean
public class BrandListener {

    @Autowired
    private CatalogServiceClient catalogServiceClient;
    @Autowired
    private ElasticTemplate elasticTemplate;

    @KafkaListener
    public void onCreateBrand(BrandCreatedEvent event) throws Exception {
        CompletableFuture<Brand> categoryCompletableFuture = catalogServiceClient.getBrand(event.getId());
        Brand brand = categoryCompletableFuture.get();
        IndexDocument doc = new IndexDocument(brand.getId());
        doc.put(BrandMapping.FIELD_ID, brand.getId());
        doc.put(BrandMapping.FIELD_NAME, brand.getName());
        doc.put(BrandMapping.FIELD_CATEGORY_ID, brand.getCategoryId());
        doc.put(BrandMapping.FIELD_DESC , brand.getDescription());
        doc.put(BrandMapping.FIELD_LOGO , brand.getLogo());

        CreateDocumentCriteria createDocumentCriteria = new CreateDocumentCriteria();
        createDocumentCriteria.setIndex(BrandMapping.INDEX);
        createDocumentCriteria.setType(BrandMapping.TYPE);
        createDocumentCriteria.setDocument(doc);
        elasticTemplate.insert(createDocumentCriteria);
    }

}
